package com.wtao.mediaprojection;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.Toast;

/**
 * 系统类叫MediaProjectionManager，为了区别系统类取名Helper
 * <p>
 * 屏幕录制代码原本是写在Activity里的，为了减少Activity的录制功能的代码，才将录制的操作放到这个类中了
 * 使用：
 * 1、Activity界面权限申请成功后，getInstance()获取实例
 * 2、点击开始录制时 调用setConfig(Activity activity)方法， 会bindService连接service，并获取一个service映射到当前类的成员变量里，获取到映射会后调用startActivityForResult(所以setConfig参数需要是Activity对象)
 * 3、在Activity的onActivityResult回调里启动录制，调用当前类的 startRecord(int resultCode, Intent data)方法
 * 4、点击停止录制，直接调用当前类中的 stopRecord()方法
 * 5、onDestroy方法里里unBindService
 */
public class MediaProjectionHelper {
    String TAG = "MediaProjectionHelper";
    //录屏工具
    MediaProjectionManager mediaProjectionManager;
    MediaProjection mediaProjection;
    private static MediaProjectionHelper instance;
    private ScreenRecordService screenRecordService;
    private Activity mContext;
    //请求码
    public final static int REQUEST_CODE = 101;


    private MediaProjectionHelper() {

    }

    //连接服务
    public void connectService() {
        //通过intent为中介绑定Service，会自动create
        Intent intent = new Intent(mContext, ScreenRecordService.class);
        //绑定过程连接，选择绑定模式
        mContext.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    //连接服务成功与否，具体连接过程
    //调用连接接口，实现连接，回调连接结果
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            //服务连接成功，需要通过Binder获取服务，达到Activity和Service通信的目的
            //获取Binder
            ScreenRecordService.ScreenRecordBinder binder = (ScreenRecordService.ScreenRecordBinder) iBinder;
            //通过Binder获取Service
            screenRecordService = binder.getScreenRecordService();
            //获取到服务，初始化录屏管理者
            mediaProjectionManager = (MediaProjectionManager) mContext.getSystemService(Context.MEDIA_PROJECTION_SERVICE);
            Log.e(TAG, "请求系统录屏");
            //通过管理者，创建录屏请求，通过Intent
            Intent captureIntent = mediaProjectionManager.createScreenCaptureIntent();
            //将请求码作为标识一起发送，调用该接口，需有返回方法
            mContext.startActivityForResult(captureIntent, REQUEST_CODE);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            screenRecordService = null;
            //连接失败
            Toast.makeText(mContext, "录屏服务未连接成功，请重试！", Toast.LENGTH_SHORT).show();
        }
    };

    public static MediaProjectionHelper getInstance() {
        if (instance == null) {
            instance = new MediaProjectionHelper();
        }
        return instance;
    }

    //设置配置信息同时连接服务
    public void setConfig(Activity context) {
        this.mContext = context;
        if (screenRecordService == null) {
            Log.e(TAG, "null ,绑定服务");
            connectService();
        } else {
            //已经获取了映射对象，点击想用开启录制，就可以直接startRecord()
            startRecord();
        }
    }

    //开始录制
    public void startRecord(int resultCode, Intent data) {
        mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
        //将该工具给Service，并一起传过去需要录制的屏幕范围的参数
        if (screenRecordService != null) {
            Log.e(TAG, "onActivityResult screenRecordService != null");
            screenRecordService.setMediaProjection(mediaProjection);
            //获取录屏屏幕范围参数
            DisplayMetrics metrics = new DisplayMetrics();
            mContext.getWindowManager().getDefaultDisplay().getMetrics(metrics);
            Log.e(TAG, "onActivityResult "+metrics.widthPixels+" "+ metrics.heightPixels+" "+ metrics.densityDpi);
            screenRecordService.setConfig(metrics.widthPixels, metrics.heightPixels, metrics.densityDpi);
            //开始录制
            screenRecordService.startRecord();
            Toast.makeText(mContext, "开始录制，录制中..", Toast.LENGTH_SHORT).show();
        } else {
            Log.e(TAG, "onActivityResult screenRecordService = null");
        }
    }

    public void startRecord() {
        if (screenRecordService != null && !screenRecordService.isRunning()) {
            //没有录制，就开始录制，弹出提示，返回主界面开始录制
            screenRecordService.startRecord();
            Log.e(TAG, "开始录制");
            Toast.makeText(mContext, "录制已开始", Toast.LENGTH_SHORT).show();
        } else {
            if (screenRecordService != null && screenRecordService.isRunning()) {
                Toast.makeText(mContext, "当前已经在录制，停止后再开始", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //停止录制
    public void stopRecord() {
        if (screenRecordService != null && screenRecordService.isRunning()) {
            screenRecordService.stopRecord();
            Toast.makeText(mContext, "停止录制", Toast.LENGTH_SHORT).show();
        }
    }

    public boolean isRecoding() {
        if (screenRecordService != null) {
            return screenRecordService.isRunning();
        } else {
            return false;
        }
    }
    public void unBindService(){
        if (screenRecordService != null) {
            mContext.unbindService(serviceConnection);
        }
    }
}
